//
//  LLItemSlider.swift
//  LaiLang
//
//  Created by David on 2017/2/17.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

@objc protocol LLItemSliderDataSource {
    func itemSlider(rowNumForItemSlider: LLItemSlider) -> Int
    func itemSlider(itemSlider: LLItemSlider, itemForRow at: Int) -> UIButton
    @objc optional func itemSlider(itemSizeForSlider: LLItemSlider) -> CGFloat
    @objc optional func itemSlider(itemSlider: LLItemSlider, didClickItem at: Int)
    @objc optional func itemSlider(spacingForItemSlider: LLItemSlider) -> CGFloat
}

class LLItemSlider: UIScrollView {
    private var _dataSource: LLItemSliderDataSource?
    var dataSource: LLItemSliderDataSource?{
        get{
            return _dataSource
        }
        set(f){
            _dataSource = f
            reloadData()
        }
    }
    
    
    var stackView: UIStackView?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        alwaysBounceHorizontal = true
    }
    
    func reloadData(){
        let count = dataSource?.itemSlider(rowNumForItemSlider: self)
        if count == nil{
            return
        }
        let itemSize = dataSource?.itemSlider?(itemSizeForSlider: self) ?? 44
        if stackView != nil{
            stackView?.removeFromSuperview()
        }
        let spacing  = dataSource?.itemSlider?(spacingForItemSlider: self) ?? 0
        stackView = UIStackView(frame: CGRect(x: 0, y: 0, width: itemSize * CGFloat(count!) + spacing * CGFloat(count! - 1), height: itemSize))
        stackView?.axis = .horizontal
        stackView?.distribution = .fillEqually
        stackView?.spacing = spacing
        contentSize = CGSize(width: itemSize * CGFloat(count!) + spacing * CGFloat(count! - 1), height: itemSize)
        for i in 0..<count!{
            let item = dataSource?.itemSlider(itemSlider: self, itemForRow: i)
            if item != nil{
                item?.tag = i
                item?.addTarget(self, action: #selector(LLItemSlider.itemClick(sender:)), for: .touchUpInside)
                stackView?.addArrangedSubview(item!)
            }
        }
        addSubview(stackView!)
        
    }
    
    private var _selectedIndex: Int = -1
    var selectedIndex: Int{
        get{
            return _selectedIndex
        }
        set(i){
            _selectedIndex = i
            reloadData()
        }
    }
    
    func itemClick(sender: UIButton){
        
        dataSource?.itemSlider?(itemSlider: self, didClickItem: sender.tag)
        selectedIndex = sender.tag
    }
    
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
